use crate::db_source::get_mysql_conn_pool;
use mysql_common::params;
use serde::Serialize;

#[derive(Serialize)]
pub struct Brand {
    pub id: u16,
    pub name: Option<String>,
    pub desc: Option<String>,
    pub pic_url: Option<String>,
    pub sort_order: u8,
    pub floor_price: f32,
    pub deleted:u8,
}

impl Brand {
    ///new
    pub fn new(id: u16, name: Option<String>,desc:Option<String>,pic_url:Option<String>,sort_order:u8,
        floor_price:f32,deleted:u8) -> Brand {
        Brand { id, name,desc,pic_url,sort_order,floor_price,deleted }
    }
    ///insert
    pub fn insert(brand: Brand) -> u16 {
        let mysql_conn_pool = get_mysql_conn_pool().unwrap();
        let sql = r"INSERT INTO litemall.litemall_brand
        (name,desc,pic_url,sort_order,floor_price,deleted)
        VALUES
        (:name,:desc,:pic_url,:sort_order,:floor_price,:deleted)";
        let _result = mysql_conn_pool
            .prep_exec(sql, params! {"name" => brand.name,"desc" => brand.desc,"pic_url" => brand.pic_url,"sort_order" => brand.sort_order,
            "floor_price" => brand.floor_price,"deleted" => brand.deleted,})
            .expect("");
        1
    }
    ///select_by_id
    pub fn select_by_id(id: u16) -> Option<Brand> {
        let mysql_conn_pool = get_mysql_conn_pool().unwrap();
        let sql = "SELECT id, name,desc,pic_url,sort_order,floor_price,deleted from litemall.litemall_brand where id = :id";
        let p = params!("id" => id);
        let mut selected: Vec<Brand> = mysql_conn_pool
            .prep_exec(sql, p)
            .map(|result| {
                result
                    .map(|x| x.unwrap())
                    .map(|row| {
                        let (id, name,desc,pic_url,sort_order,floor_price,deleted) = mysql::from_row(row);
                        Brand { id, name,desc,pic_url,sort_order,floor_price,deleted }
                    })
                    .collect()
            })
            .unwrap();
        let option = selected.pop();
        option
    }
}
